package com.dodo.blog.ui.ajax;

import com.dodo.blog.RequestCycle;
import com.dodo.blog.ui.ajax.annotation.GetModel;
import com.dodo.blog.ui.page.Page;
import org.codehaus.jackson.map.ObjectMapper;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Logger;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public abstract class AbstractAjaxRequestHandler
        implements IAjaxRequestHandler
{

    private static final long serialVersionUID = 1L;

    protected Logger log = Logger.getLogger( AbstractAjaxRequestHandler.class.getName() );

    public static ObjectMapper MAPPER = new ObjectMapper();

    protected Object getModelObject( Page page, String modelId )
            throws InvocationTargetException, IllegalAccessException
    {
        for ( Method method : page.getClass().getDeclaredMethods() )
        {
            GetModel getModelAnnotation = method.getAnnotation( GetModel.class );
            if ( getModelAnnotation != null && getModelAnnotation.name().equals( modelId ) )
            {
                return method.invoke( page );
            }
        }

        throw new NullPointerException( "Model object cannot be null! Check if method annotated with " + GetModel.class.getName() + "('" + modelId + "') returns not null object." );
    }

    protected Class<? extends Page> getPageClass()
    {
        String path = RequestCycle.get().getRequest().getServletPath();
        return RequestCycle.get().getWebApplication().getPageClassByPath( path );
    }
}
